import 'dart:async';
import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';
import 'package:x3_form_core/enums/base_advanced_filter_type.dart';
import 'package:x3_form_core/models/base_advanced_filter_model.dart';
import 'package:x3_form_core/provider/base_advanced_filter_provider.dart';
import 'package:x3_component_core/components/button_components/base_button.dart';

import 'components/advanced_filter_choice_date_range.dart';
import 'components/advanced_filter_input_search_single_choice.dart';
import 'components/advanced_filter_multi_choice_style_two.dart';
import 'components/advanced_filter_single_choice_style_two.dart';

class BaseHeadAdvancedFilter extends StatefulWidget {
  final BaseAdvancedFilterProvider baseAdvancedFilterProvider;
  final Map<String, dynamic> resetData;
  final Function(Map<String, dynamic>) onComplete;
  final double minHeight;
  final double maxHeight;
  final double distanceToAppbar;

  const BaseHeadAdvancedFilter({
    Key key,
    @required this.baseAdvancedFilterProvider,
    @required this.onComplete,
    this.resetData,
    this.maxHeight,
    this.minHeight = 200,
    this.distanceToAppbar,
  }) : super(key: key);

  @override
  _BaseHeadAdvancedFilterState createState() => _BaseHeadAdvancedFilterState();
}

class _BaseHeadAdvancedFilterState extends State<BaseHeadAdvancedFilter> {
  ///标题栏（appbar）
  static double _appbarHeight = 0.0;

  BaseAdvancedFilterProvider get provider => widget.baseAdvancedFilterProvider;
  StreamController _resetStreamController = StreamController<bool>.broadcast();

  @override
  void initState() {
    super.initState();
    provider.resetStream = _resetStreamController.stream as Stream<bool>;
    _appbarHeight = widget.distanceToAppbar == null ? AppBar().preferredSize.height : AppBar().preferredSize.height + widget.distanceToAppbar;
  }

  @override
  void dispose() {
    _resetStreamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: SafeArea(
        child: Center(
          child: Column(
            children: [
              SizedBox(height: _appbarHeight),
              BaseComponentUtils.buildHorizontalDivider(),
              Container(
                width: double.infinity,
                constraints: BoxConstraints(minHeight: widget.minHeight, maxHeight: widget.maxHeight == null ? MediaQuery.of(context).size.height * 0.7 : widget.maxHeight),
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                color: Colors.white,
                child: _buildContent(),
              ),
              Expanded(
                child: InkWell(
                  onTap: () {
                    BaseRouterUtil().pop();
                  },
                  child: Container(color: Color(0XAA000000)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///多选部分 BaseFilterUtils.showAdvancedFilter
  Widget _buildContent() {
    return Column(
      children: [
        SizedBox(height: 12),
        Expanded(child: _buildProvider()),
        SizedBox(height: 12),
        _buildBottomSheetButtonBar(),
        SizedBox(height: 12),
      ],
    );
  }

  Widget _buildProvider() {
    return Provider(
      create: (_) => provider,
      child: Consumer<BaseAdvancedFilterProvider>(
        builder: (BuildContext context, BaseAdvancedFilterProvider model, Widget child) {
          return ListView.separated(
            itemCount: provider.models.length,
            separatorBuilder: (BuildContext context, int index) => SizedBox(height: 16, child: Divider(height: 1)),
            itemBuilder: (context, index) {
              return catalog(model.models[index]);
            },
          );
        },
      ),
    );
  }

  Widget _buildBottomSheetButtonBar() {
    return Row(
      children: [
        Expanded(child: BaseButton(text: "取消", onPress: onCancel, fill: false)),
        SizedBox(width: 12.0),
        Expanded(child: BaseButton(text: "重置", onPress: onReset, fill: false)),
        SizedBox(width: 12.0),
        Expanded(child: BaseButton(text: "确定", onPress: onComplete, fill: false)),
      ],
    );
  }

  /// 筛选目录
  Widget catalog(BaseAdvancedFilterModel model) {
    Map<BaseAdvancedFilterType, Widget> catalog = {
      BaseAdvancedFilterType.ChoiceDateRange: AdvancedFilterChoiceDateRange(model: model),
      BaseAdvancedFilterType.SingleChoiceStyleTwo: AdvancedFilterSingleChoiceStyleTwo(model: model),
      BaseAdvancedFilterType.MultipleChoiceStyleTwo: AdvancedFilterMultiChoiceStyleTwo(model: model),
      BaseAdvancedFilterType.InputSearchSingleChoice: AdvancedFilterInputSearchSingleChoice(model: model),
      BaseAdvancedFilterType.InputSearchMultipleChoice: AdvancedFilterInputSearchSingleChoice(model: model),
      // BaseAdvancedFilterType.InputTextRange: AdvancedFilterInputTextRange(model: model),
      // BaseAdvancedFilterType.InputText: AdvancedFilterInputText(model: model),
    };
    return catalog[model.inputType];
  }

  void onCancel() {
    BaseRouterUtil.getInstance().pop();
  }

  void onReset() {
    provider.dataSource.clear();
    if (widget.resetData != null) provider.dataSource.addAll(widget.resetData);
    this._resetStreamController.sink.add(true);
  }

  void onComplete() async {
    bool validationDataSourceState = provider.validationDataSource();
    if (!validationDataSourceState) return;
    bool choiceDateRangeOperateSituationState = await dealWithChoiceDateRangeOperateSituation();
    if (!choiceDateRangeOperateSituationState) return;
    widget.onComplete(provider.dataSource);
    BaseRouterUtil.getInstance().pop();
  }

  /// 如果 开始时间/结束时间 需要同时选择则提示，并且拦截确定时事件
  Future<bool> dealWithChoiceDateRangeOperateSituation() async {
    int _index = 0;
    while (_index <= widget.baseAdvancedFilterProvider.models.length - 1) {
      BaseAdvancedFilterModel filterModel = widget.baseAdvancedFilterProvider.models[_index];
      if (filterModel.inputType == BaseAdvancedFilterType.ChoiceDateRange) {
        String operateSituation = BaseUtils.getKeyData(filterModel.otherParam, "operateSituation");
        if (operateSituation == "all") {
          String fieldName = filterModel.fieldName;
          var choiceDateRangeData = provider.dataSource[fieldName] ?? {};
          String start = BaseUtils.getKeyData(choiceDateRangeData, 'startTime');
          String end = BaseUtils.getKeyData(choiceDateRangeData, 'endTime');
          DateTime startTime = DateTime.tryParse(start);
          DateTime endTime = DateTime.tryParse(end);
          if (startTime != null && endTime == null) {
            BaseUtils.showToast("请选择[${filterModel.name}] 的 [结束时间]");
            return false;
          }
          if (startTime == null && endTime != null) {
            BaseUtils.showToast("请选择[${filterModel.name}] 的 [开始时间]");
            return false;
          }
        }
      }
      _index++;
    }
    return true;
  }
}
